package pers.xiaojun.boot.module.system.service.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.xiaojun.boot.common.exception.BusinessException;
import pers.xiaojun.boot.common.util.BeanUtils;
import pers.xiaojun.boot.module.infra.service.file.FileService;
import pers.xiaojun.boot.module.system.controller.dept.vo.dept.DeptSimpleRespVO;
import pers.xiaojun.boot.module.system.controller.dept.vo.post.PostSimpleRespVO;
import pers.xiaojun.boot.module.system.controller.permission.vo.role.RoleSimpleRespVO;
import pers.xiaojun.boot.module.system.controller.user.vo.profile.UserProfileRespVO;
import pers.xiaojun.boot.module.system.controller.user.vo.profile.UserProfileUpdateReqVO;
import pers.xiaojun.boot.module.system.dao.entity.permission.RoleDO;
import pers.xiaojun.boot.module.system.dao.entity.user.AdminUserDO;
import pers.xiaojun.boot.module.system.service.dept.DeptService;
import pers.xiaojun.boot.module.system.service.dept.PostService;
import pers.xiaojun.boot.module.system.service.dept.UserPostService;
import pers.xiaojun.boot.module.system.service.permission.PermissionService;

import java.util.List;

/**
 * 用户资料服务层实现
 *
 * @author xiaojun
 * @since 2025-11-12
 */
@Service
@RequiredArgsConstructor
@Log4j2
public class UserProfileServiceImpl implements UserProfileService {

    private final UserService userService;
    private final PostService postService;
    private final UserPostService userPostService;
    private final DeptService deptService;
    private final PermissionService permissionService;
    private final FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserProfile(Long userId, UserProfileUpdateReqVO updateVO) {
        // 校验用户是否存在
        AdminUserDO userDO = userService.validateUserExists(userId);

        AdminUserDO user = BeanUtil.toBean(updateVO, AdminUserDO.class);

        if (!userDO.getAvatar().equals(user.getAvatar())) {
            // 删除旧头像
            try {
                fileService.removeFileByUrl(userDO.getAvatar());
            } catch (BusinessException ex) {
                log.warn(StrUtil.format("删除旧头像失败！用户Id {} 头像地址：{}", userId, updateVO.getAvatar()), ex);
            }

        }

        user.setId(userId);
        userService.updateById(user);
    }

    @Override
    public UserProfileRespVO getUserProfile(Long userId) {
        // 校验用户是否存在
        AdminUserDO user = userService.validateUserExists(userId);

        UserProfileRespVO userProfile = BeanUtil.toBean(user, UserProfileRespVO.class);

        // 获取岗位
        List<Long> postIds = userPostService.listPostIdsByUserId(userId);
        if (CollUtil.isNotEmpty(postIds)) {
            userProfile.setPosts(BeanUtils.toBeans(
                    postService.listByIds(postIds),
                    PostSimpleRespVO.class
            ));
        }

        // 获取部门
        if (user.getDeptId() != null) {
            userProfile.setDept(BeanUtil.toBean(
                    deptService.getDeptById(user.getDeptId()),
                    DeptSimpleRespVO.class
            ));
        }

        // 获取角色
        List<RoleDO> roles = permissionService.listRolesByUserId(userId);
        if (CollUtil.isNotEmpty(roles)) {
            userProfile.setRoles(BeanUtils.toBeans(
                    roles,
                    RoleSimpleRespVO.class
            ));
        }


        return userProfile;
    }
}
